package com.benjaminwan.read.free.widget

import android.content.Context
import android.text.Spannable
import android.text.style.ClickableSpan
import android.util.AttributeSet
import android.view.MotionEvent
import androidx.appcompat.widget.AppCompatTextView

class TextViewWithLinkClickable @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : AppCompatTextView(context, attrs, defStyleAttr) {
    private var mLastClickTime: Long = 0

    /**
     * http://stackoverflow.com/a/17246463/2299887
     */
    override fun onTouchEvent(event: MotionEvent): Boolean {
        var ret = false
        val text = text
        val stext = Spannable.Factory.getInstance().newSpannable(text)
        val action = event.action
        if (action == MotionEvent.ACTION_UP ||
            action == MotionEvent.ACTION_DOWN
        ) {
            var x = event.x.toInt()
            var y = event.y.toInt()
            x -= totalPaddingLeft
            y -= totalPaddingTop
            x += scrollX
            y += scrollY
            val layout = layout
            val line = layout.getLineForVertical(y)
            val off = layout.getOffsetForHorizontal(line, x.toFloat())
            val link =
                stext.getSpans(off, off, ClickableSpan::class.java)
            if (link.size != 0) {
                if (action == MotionEvent.ACTION_UP) {
                    val currentClickTime = System.currentTimeMillis()
                    val elapsedTime = currentClickTime - mLastClickTime
                    mLastClickTime = currentClickTime
                    if (elapsedTime > MIN_CLICK_INTERVAL) {
                        try {
                            link[0].onClick(this)
                        } catch (e: Exception) {
                            //toast("发生错误 : " + e.getMessage());
                        }
                    }
                }
                ret = true
            }
        }
        return ret
    }

    companion object {
        private const val MIN_CLICK_INTERVAL: Long = 600
    }
}